package com.hanfengyi.fastdfs.web.controller;

import com.hanfengyi.fastdfs.utils.FastDfsApiOpr;
import com.hanfengyi.hrm.AjaxResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * User: Han
 * Date: 2020/2/21
 * Time: 10:56
 * Description:
 */
@RestController
@RequestMapping("/fastdfs")
public class FastDFSController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){

        String fileExtensionName = FilenameUtils.getExtension(file.getOriginalFilename());
        try {
            String filePath = FastDfsApiOpr.upload(file.getBytes(), fileExtensionName);
            return AjaxResult.me().setSuccess(true).setMessage("上传成功！").setResultObj(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败！");
        }
    }

    @PostMapping("/uploadByBytes")
    public AjaxResult uploadByBytes(@RequestBody byte[] fileBytes,@RequestParam("extName")String extName){
        try {
            String filePath = FastDfsApiOpr.upload(fileBytes, extName);
            return AjaxResult.me().setSuccess(true).setMessage("上传成功！").setResultObj(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败！");
        }
    }

    /**
     * 文件下载
     * @param fileUrl 文件路径
     * @return
     */
    @PostMapping("/download")
    public byte[] getTemplateFile(@RequestParam("fileUrl") String fileUrl){
        int index = fileUrl.indexOf("/");
        fileUrl = StringUtils.startsWith(fileUrl, "/") ?fileUrl.substring(index+1):fileUrl;

        String fileName = fileUrl.substring(fileUrl.indexOf("/")+1);
        String groupName =  fileUrl.substring(0,fileUrl.indexOf("/"));

        return FastDfsApiOpr.download(groupName, fileName);
    }
}